import { Request, Response } from 'express'
import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcryptjs'
import { logger } from '../services/logger'

const prisma = new PrismaClient()

// 获取当前用户信息
export const getCurrentUser = async (req: Request, res: Response) => {
    try {
        const userId = req.user?.id

        const user = await prisma.user.findUnique({
            where: { id: userId },
            select: {
                id: true,
                email: true,
                username: true,
                role: true,
                avatar: true,
                createdAt: true,
                updatedAt: true
            }
        })

        if (!user) {
            return res.status(404).json({ error: '用户不存在' })
        }

        res.json(user)
    } catch (error) {
        logger.error('Get current user failed:', error)
        res.status(500).json({ error: '获取用户信息失败' })
    }
}

// 更新用户信息
export const updateUser = async (req: Request, res: Response) => {
    try {
        const userId = req.user?.id
        const { username, currentPassword, newPassword } = req.body

        const user = await prisma.user.findUnique({
            where: { id: userId }
        })

        if (!user) {
            return res.status(404).json({ error: '用户不存在' })
        }

        // 如果要修改密码，验证当前密码
        if (currentPassword && newPassword) {
            const isValidPassword = await bcrypt.compare(currentPassword, user.password)
            if (!isValidPassword) {
                return res.status(401).json({ error: '当前密码错误' })
            }
        }

        // 更新用户信息
        const updateData: any = {}
        if (username) {
            updateData.username = username
        }
        if (newPassword) {
            updateData.password = await bcrypt.hash(newPassword, 10)
        }

        const updatedUser = await prisma.user.update({
            where: { id: userId },
            data: updateData,
            select: {
                id: true,
                email: true,
                username: true,
                role: true,
                avatar: true,
                createdAt: true,
                updatedAt: true
            }
        })

        res.json(updatedUser)
    } catch (error) {
        logger.error('Update user failed:', error)
        res.status(500).json({ error: '更新用户信息失败' })
    }
}

// 更新头像
export const updateAvatar = async (req: Request, res: Response) => {
    try {
        const userId = req.user?.id
        const avatarUrl = req.file?.path // 假设使用了multer处理文件上传

        if (!avatarUrl) {
            return res.status(400).json({ error: '请上传头像' })
        }

        const updatedUser = await prisma.user.update({
            where: { id: userId },
            data: { avatar: avatarUrl },
            select: {
                id: true,
                email: true,
                username: true,
                role: true,
                avatar: true
            }
        })

        res.json(updatedUser)
    } catch (error) {
        logger.error('Update avatar failed:', error)
        res.status(500).json({ error: '更新头像失败' })
    }
} 